import {getApi} from "./http";
import {loginWxampForWechatFun} from "./util";

export const request = <T = any>(url: string, params: any) => {
    return new Promise<T>((resolve, reject) => {
        const app = getApp();
        wx.request<T>({
            url: getApi() + url,
            header: {
                satoken: app.globalData.satoken
            },
            ...params,
            success: (result) => {
                if (result && result.statusCode == 200) {
                    //一定要先判断status==200再接收值，这是小程序的规则决定的。
                    const {code, msg} = result.data as T

                    if (code == 0) {
                        resolve(result.data as T)
                    } else if (code == 50) {
                        //用户登录过期，重新登录
                        wx.login({
                            success: res => {
                                loginWxampForWechatFun(res.code);
                            },
                        })
                        return reject(msg);
                    } else {
                        reject(result.data?.msg || '获取失败'); //响应失败就执行reject()
                    }
                } else {
                    reject(result.data?.msg || '获取失败'); //响应失败就执行reject()
                }
            }, fail: (err) => {
                reject(err)
            }, complete: function (res) {

            }
        })
    })
}